﻿using System;
using System.Diagnostics;
using Soundteller.Audio.Model;
using Soundteller.Audio.Repositories.Interfaces;
using Soundteller.Audio.Services.Interfaces;
using Soundteller.Bus.Services.Interfaces;

namespace Soundteller.Audio.Services
{
    public class SoundPlayer : ISoundPlayer
    {
        private readonly ISoundBufferRepository _soundBufferRepository;
        private readonly IPublisher _publisher;

        public SoundPlayer(ISoundBufferRepository soundBufferRepository, IPublisher publisher)
        {
            if (soundBufferRepository == null) throw new ArgumentNullException("soundBufferRepository");
            if (publisher == null) throw new ArgumentNullException("publisher");

            _soundBufferRepository = soundBufferRepository;
            _publisher = publisher;
        }

        public Sound PopSoundBuffer()
        {
            Debug.WriteLine("{0}.PopSoundBuffer( {1} )", GetType().Namespace, null);

            if(_soundBufferRepository.Peek() == null)
                return null;

            var sound = _soundBufferRepository.Pop();

            _publisher.Publish(new SoundPlayedMessage { SoundName = sound.Name });

            return sound;
        }
    }
}